/**
 * 增值税发票进项记录 - 新增或编辑界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Vat.IncomeEditForm", {
  extend: "PSI.AFX.Form.EditForm",

  config: {
    companyId: "",
    companyName: "",
  },

  /**
   * 初始化组件
   * 
   * @override
   */
  initComponent() {
    const me = this;

    const entity = me.getEntity();

    me._adding = entity == null;

    const buttons = [];
    if (!entity) {
      const btn = {
        text: "保存并继续新建",
        ...PSI.Const.BTN_STYLE,
        formBind: true,
        handler() {
          me._onOK(true);
        },
        scope: me
      };

      buttons.push(btn);
    }

    let btn = {
      id: me.buildId(me, "btnOK"),
      text: "保存",
      ...PSI.Const.BTN_STYLE,
      formBind: true,
      iconCls: "PSI-button-ok",
      handler() {
        me._onOK(false);
      },
      scope: me
    };
    buttons.push(btn);

    btn = {
      id: me.buildId(me, "btnCancel"),
      text: entity == null ? "关闭" : "取消",
      ...PSI.Const.BTN_STYLE,
      handler() {
        me.close();
      },
      scope: me
    };
    buttons.push(btn);

    const t = entity == null ? "新建发票记录" : "编辑发票记录";
    const logoHtml = me.genLogoHtml(entity, t);

    PCL.apply(me, {
      header: {
        title: me.formatTitle(PSI.Const.PROD_NAME),
        height: 40
      },
      width: 800,
      height: 360,
      layout: "border",
      listeners: {
        show: {
          fn: me._onWndShow,
          scope: me
        },
        close: {
          fn: me._onWndClose,
          scope: me
        }
      },
      items: [{
        region: "north",
        height: 60,
        border: 0,
        html: logoHtml
      }, {
        region: "center",
        border: 0,
        id: me.buildId(me, "editForm"),
        xtype: "form",
        layout: {
          type: "table",
          columns: 2,
          tableAttrs: PSI.Const.TABLE_LAYOUT,
        },
        height: "100%",
        bodyPadding: 5,
        defaultType: 'textfield',
        fieldDefaults: {
          labelWidth: 85,
          labelAlign: "right",
          labelSeparator: "",
          msgTarget: 'side',
          width: 370,
          margin: "5"
        },
        items: [{
          xtype: "hidden",
          name: "id",
          value: entity == null ? null : entity.get("id")
        }, {
          xtype: "hidden",
          name: "companyId",
          value: me.getCompanyId(),
        }, {
          xtype: "displayfield",
          fieldLabel: "组织机构",
          labelWidth: 70,
          colspan: 2,
          value: me.toFieldNoteText(me.getCompanyName()),
        }, {
          id: me.buildId(me, "editRef"),
          fieldLabel: "发票号",
          labelWidth: 70,
          allowBlank: false,
          blankText: "没有输入发票号",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          name: "ref",
          value: entity == null ? null : entity.get("ref"),
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          },
        }, {
          id: me.buildId(me, "editStatus"),
          xtype: "combo",
          queryMode: "local",
          editable: false,
          valueField: "id",
          labelWidth: 70,
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "状态",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          name: "status",
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: me._adding ? [[0, "待认证"], [1000, "已认证待核销"]]
              : [[0, "待认证"], [1000, "已认证待核销"], [3000, "已核销"]],
          }),
          value: 0,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editCategory"),
          xtype: "combo",
          queryMode: "local",
          editable: false,
          valueField: "id",
          labelWidth: 70,
          fieldLabel: "发票类型",
          name: "category",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          store: PCL.create("PCL.data.ArrayStore", {
            fields: ["id", "text"],
            data: [[1, "增值税专用发票"], [2, "增值税普通发票"], [3, "增值税普通发票(可抵扣)"]]
          }),
          value: 1,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editDT"),
          xtype: "datefield",
          format: "Y-m-d",
          labelAlign: "right",
          labelSeparator: "",
          fieldLabel: "开票日期",
          allowBlank: false,
          blankText: "没有输入开票日期",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          name: "dt",
          labelWidth: 70,
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editSupplier"),
          xtype: "psi_supplierfield",
          parentCmp: me,
          showModal: true,
          labelAlign: "right",
          labelSeparator: "",
          labelWidth: 70,
          fieldLabel: "供应商",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          allowBlank: false,
          blankText: "没有输入供应商",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "hiddenSupplierId"),
          xtype: "hidden",
          name: "supplierId",
        }, {
          id: me.buildId(me, "editGoodsMoney"),
          fieldLabel: "金额(元)",
          labelWidth: 70,
          allowBlank: false,
          blankText: "没有输入金额",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          xtype: "numberfield",
          hideTrigger: true,
          name: "goodsMoney",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          id: me.buildId(me, "editTax"),
          fieldLabel: "税款(元)",
          labelWidth: 70,
          allowBlank: false,
          blankText: "没有输入税款",
          beforeLabelTextTpl: PSI.Const.REQUIRED,
          xtype: "numberfield",
          hideTrigger: true,
          name: "tax",
          listeners: {
            specialkey: {
              fn: me.__onEditSpecialKey,
              scope: me
            }
          }
        }, {
          fieldLabel: "备注",
          name: "memo",
          labelWidth: 70,
          id: me.buildId(me, "editMemo"),
          listeners: {
            specialkey: {
              fn: me._onLastEditSpecialKey,
              scope: me
            }
          },
        }],
        buttons,
      }]
    });

    me.callParent(arguments);

    me.editForm = PCL.getCmp(me.buildId(me, "editForm"));

    me.editRef = PCL.getCmp(me.buildId(me, "editRef"));
    me.editStatus = PCL.getCmp(me.buildId(me, "editStatus"));
    me.editSupplier = PCL.getCmp(me.buildId(me, "editSupplier"));
    me.editDT = PCL.getCmp(me.buildId(me, "editDT"));
    me.editGoodsMoney = PCL.getCmp(me.buildId(me, "editGoodsMoney"));
    me.editTax = PCL.getCmp(me.buildId(me, "editTax"));
    me.editCategory = PCL.getCmp(me.buildId(me, "editCategory"));
    me.editMemo = PCL.getCmp(me.buildId(me, "editMemo"));

    me.hiddenSupplierId = PCL.getCmp(me.buildId(me, "hiddenSupplierId"));

    me.btnOK = PCL.getCmp(me.buildId(me, "btnOK"));
    me.btnCancel = PCL.getCmp(me.buildId(me, "btnCancel"));

    // AFX
    me.__editorList = [
      me.editRef, me.editStatus, me.editCategory, me.editDT, me.editSupplier,
      me.editGoodsMoney, me.editTax, me.editMemo];
  },

  /**
   * 保存
   * 
   * @private
   */
  _onOK(thenAdd) {
    const me = this;

    const supplierId = me.editSupplier.getIdValue();
    me.hiddenSupplierId.setValue(supplierId);

    const f = me.editForm;
    const el = f.getEl();
    el.mask(PSI.Const.SAVING);
    const sf = {
      url: me.URL("SLN0001/Vat/editVatIncome"),
      method: "POST",
      success(form, action) {
        me._lastId = action.result.id;

        el.unmask();

        me.tip("数据保存成功", !thenAdd);
        me.focus();
        if (thenAdd) {
          me.clearEdit();
        } else {
          me.close();
        }
      },
      failure(form, action) {
        el.unmask();
        me.showInfo(action.result.msg, () => {
          me.editRef.focus();
        });
      }
    };
    f.submit(sf);
  },

  /**
   * @private
   */
  _onLastEditSpecialKey(field, e) {
    const me = this;

    if (e.getKey() == e.ENTER) {
      const f = me.editForm;
      if (f.getForm().isValid()) {
        me._onOK(me._adding);
      }
    }
  },

  /**
   * @private
   */
  clearEdit() {
    const me = this;
    me.editRef.focus();

    const editors = [me.editRef, me.editDT, me.editGoodsMoney, me.editTax, me.editMemo];
    for (let i = 0; i < editors.length; i++) {
      const edit = editors[i];
      edit.setValue(null);
      edit.clearInvalid();
    }

    me.editSupplier.clearIdValue();
    me.editSupplier.clearInvalid();
  },

  /**
   * @private
   */
  _onWndClose() {
    const me = this;

    // AFX
    PCL.get(window).un('beforeunload', me.__onWindowBeforeUnload);

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.enable();
    }

    if (me._lastId) {
      const parentForm = me.getParentForm();
      if (parentForm) {
        parentForm.refreshMainGrid.apply(parentForm, [me._lastId]);
      }
    }
  },

  /**
   * @private
   */
  _onWndShow() {
    const me = this;

    // AFX
    PCL.get(window).on('beforeunload', me.__onWindowBeforeUnload);

    const parentForm = me.getParentForm();
    if (parentForm) {
      parentForm._keyMapMain.disable();
    }

    me.setFocusAndCursorPosToLast(me.editRef);

    if (me._adding) {
      return;
    }

    // 下面是编辑
    const el = me.getEl();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/Vat/vatIncomeInfo"),
      params: {
        id: me.getEntity().get("id")
      },
      callback(options, success, response) {
        el.unmask();
        if (success) {

          const data = me.decodeJSON(response.responseText);

          me.editRef.setValue(data.ref);
          me.editStatus.setValue(parseInt(data.status));
          me.editCategory.setValue(parseInt(data.category));
          me.editDT.setValue(data.dt);
          me.editSupplier.setIdValue(data.supplierId);
          me.editSupplier.setValue(data.supplierName);
          me.editGoodsMoney.setValue(data.goodsMoney);
          me.editTax.setValue(data.tax);
          me.editMemo.setValue(data.memo);

          // 已经核销了，把表单设置为只读状态
          if (parseInt(data.status) > 1000) {
            me.setBillReadonly();
          }
        }
      }
    });

  },

  /**
   * @private
   */
  setBillReadonly() {
    const me = this;

    me.editRef.setReadOnly(true);
    me.editStatus.setReadOnly(true);
    me.editCategory.setReadOnly(true);
    me.editDT.setReadOnly(true);
    me.editSupplier.setReadOnly(true);
    me.editGoodsMoney.setReadOnly(true);
    me.editTax.setReadOnly(true);
    me.editMemo.setReadOnly(true);

    me.btnOK.setVisible(false);
    me.btnCancel.setText("关闭");
  }
});
